﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaskelot.SP.Model.Client;
using Kaskelot.SP.Model.Client.Forms;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;

namespace Kaskelot.SP.Services.Client.Mapping
{
	public static class ClientValExtensions
	{
		public static ClientVal ToClientContract(this Val entity)
		{
			ClientVal b = new ClientVal();

			CopyFromEntity(entity, b, false);

			return b;
		}

		public static ClientVal ToMinimalClientContract(this Val entity)
		{
			ClientVal b = new ClientVal();

			CopyFromEntity(entity, b, true);

			return b;
		}

		public static Val ToContract(this ClientVal b)
		{
			Val entity = new Val();

			CopyToEntity(b, entity);

			return entity;
		}

		public static Val UpdateContract(this Val val, ValForm form)
		{
			if (val.Id == Guid.Empty)
				val.Id = Guid.NewGuid();

			val.Namn = form.Namn;
			val.ValDatum = DateTime.Parse(form.ValDatum);
			val.Aktivt = form.Aktivt;

			return val;
		}

		private static void CopyFromEntity(Val from, ClientVal to, bool minimal)
		{
			to.Id = from.Id;
			to.Namn = from.Namn;

			to.Andrad = from.Andrad != null ? from.Andrad.ToString() : null;
			to.AndradAv = from.AndradAv;
			to.Skapad = from.Skapad != null ? from.Skapad.ToString() : null;
			to.SkapadAv = from.SkapadAv;

			to.Aktivt = from.Aktivt;

			if (from.ValDatum.HasValue)
				to.ValDatum = from.ValDatum.Value.ToString("yyyy-MM-dd");
			else
				to.ValDatum = null;

			to.AndradAv = from.AndradAv;

			if (from.Skapad != null)
				to.Skapad = from.Skapad.ToShortDateString();

			if (minimal) return;
			if (from.Valkretsar != null)
			{
				to.Valkretsar = new List<ClientValkrets>();
				foreach (Valkrets v in from.Valkretsar)
				{
					to.Valkretsar.Add(v.ToMinimalClientContract());
				}
			}
		}

		private static void CopyToEntity(ClientVal from, Val to)
		{
			to.Id = from.Id;
			to.Namn = from.Namn;

			if (!String.IsNullOrEmpty(from.Andrad))
				to.Andrad = DateTime.Parse(from.Andrad);
			else
				to.Andrad = null;

			to.AndradAv = from.AndradAv;

			if (from.Skapad != null)
				to.Skapad = DateTime.Parse(from.Skapad);

			to.Aktivt = from.Aktivt;

			if (!String.IsNullOrEmpty(from.ValDatum))
				to.ValDatum = DateTime.Parse(from.ValDatum);
			else
				to.ValDatum = null;
		}
	}
}
